package de.connecttext.threadpool;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import de.connecttext.dao.solr.WikipediaSolrDao;
import de.connecttext.dao.sql.SqlDao;
import de.connecttext.exception.SqlAccessException;
import de.connecttext.model.TextDocument;
import de.connecttext.services.Stopwatch;
import de.connecttext.services.TagSelectAndRefiner;

public class ReadWriteRefineTask implements Runnable {

	private TagSelectAndRefiner tagSelectAndRefiner;
	private WikipediaSolrDao wikipediaSolrDao;
	private SqlDao sqlDao;
	private Stopwatch stopwatch;

	public static int documentsRead = 0;
	public static int documentsWritten = 0;
	public static int documentsRefined = 0;

	private int start, end, rows;
	private int elapsedTime1 = 0;
	private int elapsedTime2 = 0;
	private int elapsedTime3 = 0;
	private int taskId;

	public ReadWriteRefineTask(int start, int rows, int taskCounter)
			throws ClassNotFoundException, SQLException, SqlAccessException {
		
		this.tagSelectAndRefiner = new TagSelectAndRefiner();
		this.wikipediaSolrDao = WikipediaSolrDao.getInstance();
		this.sqlDao = SqlDao.getInstance();
		this.stopwatch = new Stopwatch();
		
		this.start = start;
		this.rows = rows;
		this.end = start + rows;
		this.taskId = taskCounter;
	}

	@Override
	public void run() {

		try {

			List<TextDocument> bufferedDocuments = new ArrayList<TextDocument>();

			for (int i = start; i < end; i++) {
				stopwatch.start();

				TextDocument document;

				document = wikipediaSolrDao.get(i);

				elapsedTime1 += stopwatch.getElapsedTime();
				stopwatch.reset();

				stopwatch.start();

				document.setTagVectors(tagSelectAndRefiner.selectAndRefineTags(
						document.getSolrId(), document.getTagVectors()));

				elapsedTime2 += stopwatch.getElapsedTime();
				stopwatch.reset();

				bufferedDocuments.add(document);

			}

			documentsRead += rows;

			stopwatch.start();
			sqlDao.writeDocuments(bufferedDocuments);

			elapsedTime3 += stopwatch.getElapsedTime();
			stopwatch.reset();
			System.out.println("Documents Read: " + documentsRead + " in "
					+ elapsedTime1 + " ms");
			System.out.println("Documents Refined: " + documentsRead + " in "
					+ elapsedTime2 + " ms");

			System.out.println("Documents Written: "
					+ sqlDao.getDocumentsWritten()
					+ ", Documents Skipped because they are empty: "
					+ sqlDao.getDocumentsSkipped() + " in " + elapsedTime3
					+ " ms ");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public int getTaskId() {
		return taskId;
	}
}
